package com.xywl.escort.view.market.skus;

import android.text.TextUtils;

import com.xywl.escort.bean.BaseSkuModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import timber.log.Timber;
import com.xywl.escort.bean.SpecResp.DataBean.SpuSpecPropertysBean.SpuSpecPropertyValuesBean;

/**
 * sku算法工具类
 *
 * @author hfk
 */
public class SkuUtil {

    /**
     * 算法入口
     *
     * @param initData 所有库存的hashMap组合
     * @return 拆分所有组合产生的所有情况（生成客户端自己的字典）
     */
    public static Map<String, BaseSkuModel> skuCollection(Map<String, BaseSkuModel> initData) {
        //用户返回数据
        HashMap<String, BaseSkuModel> result = new HashMap<>();
        // 遍历所有库存
        for (String subKey : initData.keySet()) {
            BaseSkuModel skuModel = initData.get(subKey);
            //根据；拆分skuName的组合
            String[] skuKeyAttrs = subKey.split(";");

            //获取所有的组合
            ArrayList<ArrayList<String>> combArr = combInArray(skuKeyAttrs);

            // 对应所有组合添加到结果集里面
            for (int i = 0; i < combArr.size(); i++) {
                add2SKUResult(result, combArr.get(i), skuModel);
            }

            // 将原始的库存组合也添加进入结果集里面
            String skuName = TextUtils.join(";", skuKeyAttrs);
            result.put(skuName, skuModel);
        }
        return result;
    }

    /**
     * 获取所有的组合放到ArrayList里面
     *
     * @param skuKeyAttrs 单个skuName被； 拆分的数组
     * @return ArrayList
     */
    private static ArrayList<ArrayList<String>> combInArray(String[] skuKeyAttrs) {
        if (skuKeyAttrs == null || skuKeyAttrs.length <= 0)
            return null;
        int len = skuKeyAttrs.length;
        ArrayList<ArrayList<String>> aResult = new ArrayList<>();
        for (int n = 1; n < len; n++) {
            ArrayList<Integer[]> aaFlags = getCombFlags(len, n);
            for (int i = 0; i < aaFlags.size(); i++) {
                Integer[] aFlag = aaFlags.get(i);
                ArrayList<String> aComb = new ArrayList<>();
                for (int j = 0; j < aFlag.length; j++) {
                    if (aFlag[j] == 1) {
                        aComb.add(skuKeyAttrs[j]);
                    }
                }
                aResult.add(aComb);
            }
        }
        return aResult;
    }

    /**
     * 算法拆分组合 用1和0 的移位去做控制
     * （这块需要你打印才能看的出来）
     *
     * @param len
     * @param n
     * @return
     */
    private static ArrayList<Integer[]> getCombFlags(int len, int n) {
        if (n <= 0) {
            return new ArrayList<>();
        }
        ArrayList<Integer[]> aResult = new ArrayList<>();
        Integer[] aFlag = new Integer[len];
        boolean bNext = true;
        int iCnt1;
        //初始化
        for (int i = 0; i < len; i++) {
            aFlag[i] = i < n ? 1 : 0;
        }
        aResult.add(aFlag.clone());
        while (bNext) {
            iCnt1 = 0;
            for (int i = 0; i < len - 1; i++) {
                if (aFlag[i] == 1 && aFlag[i + 1] == 0) {
                    for (int j = 0; j < i; j++) {
                        aFlag[j] = j < iCnt1 ? 1 : 0;
                    }
                    aFlag[i] = 0;
                    aFlag[i + 1] = 1;
                    Integer[] aTmp = aFlag.clone();
                    aResult.add(aTmp);
                    if (!TextUtils.join("", aTmp).substring(len - n).contains("0")) {
                        bNext = false;
                    }
                    break;
                }
                if (aFlag[i] == 1) {
                    iCnt1++;
                }
            }
        }
        return aResult;
    }

    /**
     * 添加到数据集合
     *
     * @param result
     * @param newKeyList
     * @param skuModel
     */
    private static void add2SKUResult(HashMap<String, BaseSkuModel> result, ArrayList<String> newKeyList, BaseSkuModel skuModel) {
        String skuName = TextUtils.join(";", newKeyList);
        if (result.keySet().contains(skuName)) {
            result.get(skuName).price = skuModel.price;
            result.get(skuName).originalPrice = skuModel.originalPrice;
            result.get(skuName).stock = result.get(skuName).stock + skuModel.stock;
            result.get(skuName).spuId = skuModel.spuId;
            result.get(skuName).spuName = skuModel.spuName;
            result.get(skuName).id = skuModel.id;
            result.get(skuName).skuName = skuModel.skuName;
            result.get(skuName).picture = skuModel.picture;

        } else {
            result.put(skuName, new BaseSkuModel(skuModel));
        }
    }

    /**
     * 所选规格的价格和库存展示
     *
     * @param mUiData
     */
    public static void setBabyShowData(UiData mUiData) {
        StringBuilder stringBuild = new StringBuilder();
        List<String> noChooseName = new ArrayList<>();

        for (int i = 0; i < mUiData.adapters.size(); i++) {
            if (mUiData.adapters.get(i).getCurrentSelectedItem() == null) {
                noChooseName.add(mUiData.projectType.get(i));
            }
        }
        if (noChooseName.size() > 0) {
            for (int i = 0; i < noChooseName.size(); i++) {
                if (i == 0) {
                    stringBuild.append("请选择 ");
                }
                if (i == noChooseName.size() - 1) {
                    stringBuild.append(noChooseName.get(i));
                } else {
                    stringBuild.append(noChooseName.get(i));
                    stringBuild.append(" ");
                }
            }
            mUiData.currentSkuModel = mUiData.baseSkuModel;
            mUiData.mBottomSheetDialog.showPriceAndSku(mUiData.currentSkuModel, stringBuild.toString());
        } else {
            for (int i = 0; i < mUiData.adapters.size(); i++) {
                if (i == 0) {
                    stringBuild.append("已选： ");
                }
                stringBuild.append("\"" + mUiData.adapters.get(i).getCurrentSelectedItem().name + "\" ");
            }
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < mUiData.adapters.size(); i++) {
                stringBuilder.append(mUiData.adapters.get(i).getCurrentSelectedItem().attributeMemberId);
                stringBuilder.append(";");
            }
            Timber.e(stringBuilder.toString());
            if (!TextUtils.isEmpty(stringBuilder.toString())) {
                mUiData.currentSkuModel = mUiData.result.get(stringBuilder.substring(0, stringBuilder.length() - 1));
            } else {
                mUiData.currentSkuModel = mUiData.baseSkuModel;
            }
            mUiData.mBottomSheetDialog.showPriceAndSku(mUiData.currentSkuModel, stringBuild.toString());
        }
    }

    /**
     * 如果有重复的数据，则去重;
     *
     * @param list
     * @return
     */
    public static List<SpuSpecPropertyValuesBean> ifRepeat(List<SpuSpecPropertyValuesBean> list) {
        Set<SpuSpecPropertyValuesBean> set = new HashSet<>();
        List<SpuSpecPropertyValuesBean> newList = new ArrayList<>();
        for (SpuSpecPropertyValuesBean values : list) {
            if (set.add(values)) {
                newList.add(values);
            }
        }
        Timber.tag("remove duplicate list").e(list.toString());
        return newList;
    }

    //使用String的split 方法
    public static String[] convertStrToArray(String str) {
        if (!TextUtils.isEmpty(str)) {
            return str.split(",");
        }
        return null;
    }
}